package com.service.business.framework.interceptor;

import com.service.business.support.Language;
import com.service.business.support.Token;
import com.service.business.utils.I18nUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

import static com.service.business.support.Language.LANG_KEY;

/**
 * <dl>
 * <dt>platform</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2018</dd>
 * <dd>Company: </dd>
 * <dd>CreateDate: 2019-04-04</dd>
 * </dl>
 */
@Component
@Slf4j
public class HeaderHandlerInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String lang = request.getHeader(LANG_KEY);
        log.info("requestURI:{},get lang header:{}", request.getRequestURI(), lang);
        Language.LANG.set(Optional.ofNullable(lang).orElse(I18nUtil.CLocale.zh_CN));

        String token = request.getHeader(Token.TOKEN_KEY);
        Token.TOKEN.set(Optional.ofNullable(token).orElse(null));

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Language.LANG.remove();
        Token.TOKEN.remove();
    }
}
